<?php

namespace app\controller\student;

use app\BaseController;
use app\Code;
use app\dao\HonorDao;
use think\facade\Request;
use think\facade\Filesystem;
use think\facade\Log;
use app\validate\HonorValidate;
use think\exception\ValidateException;

class ProfileController extends BaseController
{
    // 提交荣誉申请
    public function submitHonor()
    {
        $data = Request::post();
        $memberId = request()->user['member_id'] ?? null;

        // 参数验证
        try {
            validate(HonorValidate::class)->check($data);
        } catch (ValidateException $e) {
            return $this->returnJson([], Code::UNPROCESSABLE_ENTITY, $e->getMessage());
        }

        // 文件上传验证
        $file = Request::file('cert_image');
        if (!$file) {
            return $this->returnJson([], Code::BAD_REQUEST, '请上传荣誉证书');
        }

        $allowedTypes = ['image/jpeg', 'image/png'];
        if (!in_array($file->getMimeType(), $allowedTypes)) {
            return $this->returnJson([], Code::BAD_REQUEST, '文件类型不支持');
        }

        if ($file->getSize() > 1024 * 1024 * 5) {
            return $this->returnJson([], Code::BAD_REQUEST, '文件大小不能超过5MB');
        }

        try {
            $savename = Filesystem::disk('public')->putFile('honors', $file);
            $filePath = '/storage/' . $savename;

            $result = HonorDao::submitHonor(
                $memberId,
                $filePath,
                $data['description'],
                $data['title'],
                $data['date']
            );

            if ($result) {
                return $this->returnJson();
            }

            return $this->returnJson([], Code::BAD_REQUEST, '荣誉申请提交失败');
        } catch (\Exception $e) {
            Log::error("荣誉申请提交失败: " . $e->getMessage());
            return $this->returnJson([], Code::SERVER_ERROR, '服务器错误，请稍后再试');
        }
    }
}
